package com.tiantang.study.netty.reactor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author liujinkun
 * @Title: Acceptor
 * @Description: TODO
 * @date 2019/5/5 11:20 PM
 */
public class Acceptor implements Runnable{

    // server socket port
    private int port;

    private Selector selector;

    // 代表server socket,采用LinkedBlockQueue队列来模拟外部请求输入队列
    private BlockingQueue<InputSource> sourceQueue = new LinkedBlockingQueue<InputSource>();

    public Acceptor(int port,Selector selector){
        this.port = port;
        this.selector = selector;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    /**
     * 外部有输入请求后，加入到请求队列中
     * @param source
     */
    public void addNewConnection(InputSource source){
        this.sourceQueue.add(source);
    }

    public void run() {
        while(true){
            InputSource source = null;
            try {
                // 相当于serverSocket.accept(),接收输入请求，该示例从队列中获取输入请求
                source = sourceQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 接收到inputSource后，将event设置为ACCEPT事件类型，并将source赋值给event
            if(source != null){
                Event event = new Event();
                event.setEventType(EventType.ACCEPT);
                event.setInputSource(source);
                selector.addEvent(event);
            }
        }


    }
}
